import img1 from './images/1.jpeg';
import img2 from './images/2.jpeg';
import img3 from './images/3.jpeg';

const list = [img1, img2, img3];
// 面向对象 / 面向过程

// 定义一个红绿灯类
function Light(box) {
  // 装红绿灯的容器
  this.box = document.querySelector(box);
  // 初始值
  this.index = 1;
  // 判断图片标识
  this.flag = true;
  // 定时器
  this.timer;
}

// 初始化图片方法
Light.prototype.init = function () {
  console.log('初始化图片');
  // 创建图片标签
  this.img = new Image();
  // 设置图片不可拖拽
  this.img.draggable = false;
  this.img.src = `${list[this.index - 1]}`;
  // 添加到容器中
  this.box.appendChild(this.img);
};

// 绑定点击往下亮事件
Light.prototype.bindClick = function () {
  this.box.addEventListener('click', () => {
    this.index++;
    // this.index = (this.index % 3) + 1
    // 判断图片是否超出范围
    this.index > 3 && (this.index = 1);
    // 修改图片地址
    this.img.src = `${list[this.index - 1]}`;
  });
};

// 绑定点击往上亮事件
Light.prototype.bindClickReverse = function () {
  this.box.addEventListener('click', () => {
    this.index--;
    // this.index = (this.index % 3) + 1
    // 判断图片是否超出范围
    this.index < 1 && (this.index = 3);
    // 修改图片地址
    this.img.src = `${list[this.index - 1]}`;
  });
};

// 自动播放
Light.prototype.autoPlay = function () {
  // 定时器
  this.timer = setInterval(() => {
    // 根据标识控制图片上下播放
    if (this.flag) {
      this.index++;
      this.index >= 3 && (this.flag = false);
    } else {
      this.index--;
      this.index <= 1 && (this.flag = true);
    }
    // 修改图片地址
    this.img.src = `${list[this.index - 1]}`;
  }, 1000);
};

// 鼠标移入移出停止启动定时器
Light.prototype.moveFn = function () {
  this.box.addEventListener('mouseenter', () => {
    clearInterval(this.timer);
  });
  this.box.addEventListener('mouseleave', () => {
    this.autoPlay();
  });
};

// 顺序上-下
let l1 = new Light('.box1');
l1.init();
l1.bindClick();
// 自动播放上-下(可控的，鼠标移入不能播放，松开继续播放)
let l2 = new Light('.box2');
l2.init();
l2.autoPlay();
l2.moveFn();
// 顺序下-上
let l3 = new Light('.box3');
l3.init();
l3.bindClickReverse();
